package com.liuceng.mps.web.intercepter;

import com.alibaba.fastjson.JSONObject;
import com.liuceng.mps.Constants;
import com.liuceng.mps.utils.EncryptUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RequestIntercepter extends HandlerInterceptorAdapter {
  private static final Logger LOG = LoggerFactory.getLogger(RequestIntercepter.class);

  @Override
  public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response,
      final Object handler) throws Exception {
    String path = request.getRequestURI();
    if (!path.startsWith("/v1")) {
      return super.preHandle(request, response, handler);
    }
    boolean needSessionToken = needSessionToken(path);
    //
    if (needSessionToken) {
      String sessionToken = request.getParameter("session_token");
      sessionToken = sessionToken.replaceAll(" ", "+");
      String adminId = null;
      if (StringUtils.isNotBlank(sessionToken)) {
        adminId = EncryptUtils.decryptDes(sessionToken);
      }
      //
      if (StringUtils.isBlank(sessionToken) || StringUtils.isBlank(adminId)) {
        // 过滤，看相关功能是否携带session_token
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        JSONObject result = new JSONObject();
        result.put("result", "error");
        response.getWriter().print(result);
        response.getWriter().flush();
        //
        return false;
      } else {
        request.setAttribute("adminId", adminId);
      }
    }

    return super.preHandle(request, response, handler);
  }

  private boolean needSessionToken(String path) {
    if (path.contains(Constants.URI_CUSTOMERS) || path.contains(Constants.URI_SEND_AD_ID)) {
      return true;
    }
    return false;
  }
}
